package com.yazi.mxz.person.controller.shop;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.Spec;
import com.yazi.mxz.common.service.SpecService;
import com.yazi.mxz.person.data.form.shop.SpecForm;

/**
 * 商品规格
 *
 * @author mo_yq5
 * @since 2016年6月3日
 */
@Controller("shop-specController")
@RequestMapping("/shop/spec")
public class SpecController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(SpecController.class);
	
	@Resource
	SpecService specService;
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public ObjectResult<?> addDoJson(@Validated(SpecForm.Add.class) SpecForm form) throws MyException {
		Spec spec = form.get();
		log.debug("添加商品规格: name={}", spec.getName());
		ObjectResult<Long> jsonResult = new ObjectResult<Long>();
		try {
			spec = specService.addOrEditByStore(getStore(), spec);
			jsonResult.setResult(spec.getSpecId());
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("添加商品规格异常：", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		
		return jsonResult;
	}
	
	@RequestMapping("/editDo/json")
	@ResponseBody
	public StatusResult editDoJson(@Validated(SpecForm.Edit.class) SpecForm form) {
		Spec spec = form.get();
		log.debug("编辑商品规格: specId={}, name={}", spec.getSpecId(), spec.getName());
		StatusResult jsonResult = new StatusResult();
		try {
			// 设定为：只能修改名称
			Spec dest = specService.one(spec.getSpecId());
			dest.setName(spec.getName());
			specService.merge(dest);
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("编辑商品规格异常：", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		
		return jsonResult;
	}
}
